import peewee
from peewee import *
import pymysql
import configparser
def setup_database():
    config = configparser.ConfigParser()
    config.read('ENV.ini')

    # 用pymysql库创建数据库
    mydb = pymysql.connect(
        host=config.get('db', 'host'),
        port=int(config.get('db', 'port')),
        user=config.get('db', 'user'),
        password=config.get('db', 'pwd'),
        charset='utf8mb4', collation='utf8mb4_general_ci'
    )
    mycursor = mydb.cursor()
    create_db_query = f"CREATE DATABASE IF NOT EXISTS {config.get('db', 'db')}"
    mycursor.execute(create_db_query)

    def connect_to_sql():
        database = peewee.MySQLDatabase(
            database=config.get('db', 'db'),
            host=config.get('db', 'host'),
            port=int(config.get('db', 'port')),
            user=config.get('db', 'user'),
            password=config.get('db', 'pwd'),
            charset='utf8mb4', collation='utf8mb4_general_ci'
        )
        database.connect()
        return database

    db = connect_to_sql()

    def execute_sql_file(file_path):
        with open(file_path, 'r', encoding='utf-8') as sql_file:
            sql_statements = sql_file.read().split(';')  # 根据分号分割各个 SQL 语句
            sql_statements = [statement.strip() for statement in sql_statements if statement.strip()]

            # 逐个执行 SQL 语句
            for statement in sql_statements:
                db.execute_sql(statement)

    return execute_sql_file

if __name__ == "__main__":
    ##创建数据库
    execute_sql = setup_database()  # 调用 setup_database() 函数
    execute_sql('auth.sql')  # 运行 SQL 脚本